package net.aiion.weave.impl.resources.provider;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import net.aiion.weave.spi.resources.ResourceException;
import net.aiion.weave.spi.resources.provider.ResourceProvider;
import net.aiion.weave.spi.resources.provider.ResourceProviderFactory;

public class ResourceProviderFactoryImpl implements ResourceProviderFactory
{
    private static final int JAR_PREFIX_URL_OFFSET = 4;

    public ResourceProviderFactoryImpl() {
    }

    @Override
    public ResourceProvider createResourceProvider(final URL aURL) {
        try {
            return createResourceProvider1(aURL);
        } catch (final IOException e) {
            throw new ResourceException(e);
        }
    }

    private ResourceProvider createResourceProvider1(final URL aURL) throws IOException {
        final URL inputStreamURL = transformURL(aURL);

        if (!"file".equals(inputStreamURL.getProtocol())) {
            throw new ResourceException("Unable to understand protocol: " + inputStreamURL.getProtocol());
        }

        final File inputFile = new File(inputStreamURL.getPath());
        final ResourceProvider inputStreamProvider;
        if (inputFile.isDirectory()) {
            inputStreamProvider = new FileResourceProvider(inputFile);
        } else if (inputFile.isFile()) {
            inputStreamProvider = new JarResourceProvider(inputStreamURL);
        } else {
            inputStreamProvider = null;
        }

        return inputStreamProvider;
    }

    private URL transformURL(final URL aURL) throws MalformedURLException {
        final String urlString = aURL.toString();
        if (urlString.endsWith("!/")) {
            // URL is something like "jar:<some-stuff>!/" - we need only "<some-stuff>"
            return new URL(urlString.substring(JAR_PREFIX_URL_OFFSET, urlString.length() - 2));
        }

        return aURL;
    }
}
